//
// Created by 33145 on 2023/1/13.
//
#include <memory>

#include "../sylar/sylar.h"

sylar::Logger::ptr g_logger = SYLAR_LOG_ROOT();

void run_in_fiber2() {
  SYLAR_LOG_INFO(g_logger) << "run_in_fiber2 begin";
  SYLAR_LOG_INFO(g_logger) << "run_in_fiber2 end";
}

void run_in_fiber() {
  SYLAR_LOG_INFO(g_logger) << "run_in_fiber begin";

  /**
   * 非对称协程，子协程不能创建并运行新的子协程，下面的操作是有问题的，
   * 子协程再创建子协程，原来的主协程就跑飞了
   */
  sylar::Fiber::ptr fiber(new sylar::Fiber(run_in_fiber2, 0, true));
  fiber->call();

  SYLAR_LOG_INFO(g_logger) << "run_in_fiber end";
}

void test_fiber() {
  SYLAR_LOG_INFO(g_logger) << "main begin 1";
  {
    sylar::Fiber::GetThis();
    SYLAR_LOG_INFO(g_logger) << "main begin";
    sylar::Fiber::ptr fiber(new sylar::Fiber(run_in_fiber, 256, true));
    fiber->call();
    SYLAR_LOG_INFO(g_logger) << "main after swapIn";
    fiber->call();
    SYLAR_LOG_INFO(g_logger) << "main after end";
    // fiber->call();
  }
  SYLAR_LOG_INFO(g_logger) << "main after end2";
}

void func() {
  puts("1");
  puts("11");
  puts("111");
  puts("1111");
}
void test() {
  char stack[1024*4];
  ucontext_t child, main;

  getcontext(&child);
  child.uc_stack.ss_sp = stack;
  child.uc_stack.ss_size = sizeof stack;
  child.uc_stack.ss_flags = 0;
  child.uc_link = NULL;  // 后继上下文， child执行完之后会返回到main保存的上下文？
  // func执行完后会执行child的 uc_link
  makecontext(&child, func, 0);
  // 保存当前上下文到main，然后去执行child
  swapcontext(&main, &child);
  std::cout << "hello world" << std::endl;
}

int main(int argc, char** argv) {
  sylar::Thread::SetName("main");
  test_fiber();
  return 0;
}